<template>
  <div class="condition-form">
    <div class="condition-header">
      <h4>条件维度</h4>
      <div class="field-selector">
        <select 
          class="field-select"
          v-model="selectedField"
          :disabled="!availableFields.length">
          <option value="" disabled>选择维度</option>
          <option 
            v-for="field in availableFields" 
            :key="field.key" 
            :value="field.key">
            {{ field.label }}
          </option>
        </select>
        <button 
          class="add-condition-btn" 
          @click="addSelectedCondition"
          :disabled="!selectedField">
          <span class="btn-icon">+</span>
          添加
        </button>
      </div>
    </div>
    <div class="conditions-list">
      <div v-for="(condition, field) in parsedConditions" 
           :key="field" 
           class="condition-item">
        <div class="condition-row">
          <div class="field-info">
            <span class="field-name">{{ getFieldDisplayName(field) }}</span>
            <select 
              class="operator-select"
              :value="getConditionOperator(field)"
              @change="handleConditionOperatorChange(field, $event.target.value)">
              <option value="in">包含</option>
              <option value="not in">不包含</option>
            </select>
          </div>
          <button class="remove-condition" @click="removeCondition(field)">×</button>
        </div>
        <div class="value-container">
          <div class="value-tags">
            <div v-for="(val, index) in getConditionValues(field)" 
                 :key="index" 
                 class="value-tag">
              <span>{{ val }}</span>
              <button class="remove-tag" 
                      @click="removeValue(field, index)"
                      v-if="getConditionValues(field).length > 1">×</button>
            </div>
            <input 
              class="value-input"
              placeholder="输入值后按回车添加"
              @keyup.enter="addNewValue($event, field)"
              :type="getInputType(field)"
            >
          </div>
        </div>
      </div>
      
      <div v-for="(condition, field) in filterConditions" 
           :key="`filter-${field}`" 
           class="condition-item">
        <div class="condition-row">
          <span class="field-name">{{ getFieldDisplayName(field) }}</span>
          <button class="remove-condition" @click="removeCondition(field)">×</button>
        </div>
        <div class="value-container">
          <div class="numeric-input-container">
            <select 
              class="operator-select"
              :value="getNumericOperator(field)"
              @change="handleOperatorChange(field, $event.target.value)">
              <option value="gt">大于</option>
              <option value="lt">小于</option>
              <option value="gte">大于等于</option>
              <option value="lte">小于等于</option>
            </select>
            <input 
              :value="getNumericValue(field)"
              type="number"
              class="numeric-input"
              @input="handleNumericValueChange(field, $event.target.value)"
              placeholder="请输入数值"
            >
          </div>
        </div>
      </div>
    </div>
    <div class="form-actions">
      <button class="apply-btn" @click="applyChanges">应用更改</button>
    </div>
  </div>
</template>

<script>
import { API_BASE_URL } from '../config'

export default {
  name: 'ConditionForm',
  props: {
    dsl: {
      type: String,
      required: true
    },
    queryType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      parsedConditions: {},
      filterConditions: {},
      baseUrl: API_BASE_URL,
      selectedField: '',
      fieldDisplayNames: {
        year: '年份',
        month: '月份',
        province: '省份',
        city: '城市',
        product_lv1: '产品LV1',
        product_lv2: '产品LV2',
        product_lv3: '产品LV3',
        income: '收入'
      },
      numericFields: ['income', 'year', 'month']
    }
  },
  computed: {
    availableFields() {
      const usedFields = [
        ...Object.keys(this.parsedConditions),
        ...Object.keys(this.filterConditions)
      ]
      
      return Object.entries(this.fieldDisplayNames)
        .filter(([key]) => !usedFields.includes(key))
        .map(([key, label]) => ({
          key,
          label
        }))
    }
  },
  created() {
    this.initializeConditions()
  },
  methods: {
    initializeConditions() {
      try {
        const dslObj = JSON.parse(this.dsl.replace(/'/g, '"'))
        this.parsedConditions = dslObj.conditions || {}
        this.filterConditions = dslObj.filter_condition || {}
      } catch (e) {
        console.error('解析DSL失败:', e)
        this.parsedConditions = {}
        this.filterConditions = {}
      }
    },
    
    addNewValue(event, field) {
      const value = event.target.value.trim()
      if (!value) return
      
      const operator = this.getConditionOperator(field)
      const currentValues = this.getConditionValues(field)
      
      this.parsedConditions = {
        ...this.parsedConditions,
        [field]: {
          [operator]: [...currentValues, value]
        }
      }
      
      // 清空输入框
      event.target.value = ''
    },
    
    getFieldDisplayName(field) {
      return this.fieldDisplayNames[field] || field
    },
    
    getInputType(field) {
      return ['year', 'month'].includes(field) ? 'number' : 'text'
    },
    
    addSelectedCondition() {
      if (!this.selectedField) return
      
      if (this.isNumericField(this.selectedField)) {
        this.filterConditions = {
          ...this.filterConditions,
          [this.selectedField]: { gt: '' }
        }
      } else {
        this.parsedConditions = {
          ...this.parsedConditions,
          [this.selectedField]: { in: [] }
        }
      }
      
      // 清空选择
      this.selectedField = ''
    },
    
    removeCondition(field) {
      if (this.isNumericField(field)) {
        const newFilters = { ...this.filterConditions }
        delete newFilters[field]
        this.filterConditions = newFilters
      } else {
        const newConditions = { ...this.parsedConditions }
        delete newConditions[field]
        this.parsedConditions = newConditions
      }
    },
    
    removeValue(field, index) {
      const operator = this.getConditionOperator(field)
      const newValues = [...this.getConditionValues(field)]
      newValues.splice(index, 1)
      
      this.parsedConditions = {
        ...this.parsedConditions,
        [field]: {
          [operator]: newValues
        }
      }
    },
    
    isNumericField(field) {
      return this.numericFields.includes(field)
    },
    
    handleNumericValueChange(field, value) {
      const operator = this.getNumericOperator(field)
      this.filterConditions = {
        ...this.filterConditions,
        [field]: {
          [operator]: value
        }
      }
    },
    
    async applyChanges() {
      try {
        const newDsl = {
          ...JSON.parse(this.dsl.replace(/'/g, '"')),
          conditions: this.parsedConditions,
          filter_condition: this.filterConditions
        }
        
        const response = await fetch(`${this.baseUrl}/api/result-generate`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            dsl: JSON.stringify(newDsl),
            query_type: this.queryType
          })
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const result = await response.json()
        this.$emit('conditions-updated', result)
      } catch (error) {
        console.error('应用更改失败:', error)
      }
    },
    
    getNumericOperator(field) {
      const condition = this.filterConditions[field]
      return Object.keys(condition)[0] || 'gt'
    },
    
    getNumericValue(field) {
      const condition = this.filterConditions[field]
      const operator = this.getNumericOperator(field)
      return condition[operator]
    },
    
    handleOperatorChange(field, newOperator) {
      const currentValue = this.getNumericValue(field)
      this.filterConditions = {
        ...this.filterConditions,
        [field]: {
          [newOperator]: currentValue
        }
      }
    },
    
    getConditionOperator(field) {
      const condition = this.parsedConditions[field]
      return Object.keys(condition)[0] || 'in'
    },
    
    getConditionValues(field) {
      const condition = this.parsedConditions[field]
      const operator = this.getConditionOperator(field)
      return condition[operator] || []
    },
    
    handleConditionOperatorChange(field, newOperator) {
      const currentValues = this.getConditionValues(field)
      this.parsedConditions = {
        ...this.parsedConditions,
        [field]: {
          [newOperator]: currentValues
        }
      }
    }
  }
}
</script>

<style scoped>
.condition-form {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.condition-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.condition-header h4 {
  margin: 0;
  color: #1565c0;
  font-size: 15px;
  font-weight: 500;
}

.field-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.field-select {
  padding: 4px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  font-size: 13px;
  color: #475569;
  background: #fff;
  min-width: 120px;
  cursor: pointer;
}

.field-select:hover:not(:disabled) {
  border-color: #bbdefb;
}

.field-select:disabled {
  background: #f1f5f9;
  cursor: not-allowed;
}

.add-condition-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  background: #e3f2fd;
  border: 1px solid #bbdefb;
  border-radius: 4px;
  color: #1565c0;
  font-size: 13px;
  cursor: pointer;
}

.add-condition-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f1f5f9;
  border-color: #e2e8f0;
  color: #94a3b8;
}

.add-condition-btn:not(:disabled):hover {
  background: #bbdefb;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.conditions-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.condition-item {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 8px;
}

.condition-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.field-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.field-name {
  font-weight: 500;
  color: #1e293b;
  font-size: 14px;
  min-width: 80px;
}

.operator-select {
  padding: 4px 8px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  font-size: 13px;
  color: #475569;
  background: #f8fafc;
  cursor: pointer;
}

.operator-select:hover {
  border-color: #bbdefb;
}

.value-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.value-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  width: 100%;
}

.value-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  background: #e3f2fd;
  border: 1px solid #bbdefb;
  border-radius: 4px;
  font-size: 13px;
  color: #1565c0;
}

.remove-tag {
  background: none;
  border: none;
  color: #94a3b8;
  cursor: pointer;
  padding: 0 2px;
  font-size: 12px;
}

.value-input, .single-value-input {
  padding: 4px 8px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  font-size: 13px;
  flex: 1;
  min-width: 100px;
}

.remove-condition {
  background: none;
  border: none;
  color: #94a3b8;
  cursor: pointer;
  font-size: 16px;
  padding: 2px 6px;
}

.form-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.apply-btn {
  padding: 6px 16px;
  background: #1565c0;
  border: none;
  border-radius: 4px;
  color: white;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.apply-btn:hover {
  background: #1976d2;
}

/* 添加一些交互效果 */
.add-condition-btn:hover,
.value-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.remove-tag:hover,
.remove-condition:hover {
  color: #ef4444;
}

.numeric-input-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.numeric-input {
  padding: 4px 8px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  font-size: 13px;
  width: 120px;
}
</style> 